﻿using GalaSoft.MvvmLight.Messaging;
using HRM.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HRM.Model
{
    public class AuthenticationService : IAuthenticationService
    {
        public bool Add(NhomNguoiDung group, ChucNang function)
        {
            using (HRMEntities entities = new HRMEntities())
            {
                var query = entities.PhanQuyens.Where(x => x.MaNhom == group.MaNhom).FirstOrDefault();
                if (query != null)
                {
                    int count = entities.NhomNguoiDungs
                        .Where(x => x.MaNhom == query.MaNhom)
                        .Join(entities.PhanQuyens, g => g.MaNhom, a => a.MaNhom, (g, a) => a)
                        .Where(p => p.MaChucNang == function.MaChucNang).Count<PhanQuyen>();
                    if (count == 0)
                    {
                        query.MaChucNang = function.MaChucNang;
                        query.MaNhom = group.MaNhom;
                        entities.PhanQuyens.Add(query);
                        entities.SaveChanges();
                        Messenger.Default.Send(new StatusMessage("Thay đổi thành công", 3000, StatusType.Done));
                        return true;
                    }
                }
                return false;
            }
        }

        public bool Delete(NhomNguoiDung group, ChucNang function)
        {
            using (HRMEntities entities = new HRMEntities())
            {
                var query = entities.PhanQuyens.Where(x => x.MaNhom == group.MaNhom).Where(x => x.MaChucNang == function.MaChucNang).FirstOrDefault();
                if (query != null)
                {
                    entities.PhanQuyens.Remove(query);
                    entities.SaveChanges();
                    Messenger.Default.Send(new StatusMessage("Thay đổi thành công", 3000, StatusType.Done));
                    return true;
                }
                return false;
            }
        }
    }
}
